import java.net.DatagramSocket;
import java.net.SocketAddress;

public class shiyan2_2 {
    private static DatagramSocket mSocket;

    public static void main(String[] args) {
        try {
            // 1.初始化DatagramSocket，指定端口号
            mSocket = new DatagramSocket(8000);
            // 2.创建用于接收消息的DatagramPacket，指定接收数据大小

            // 3.接收客户端消息
            while(true) {
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                mSocket.receive(receivePacket);// 在接收到信息之前，一直保持阻塞状态
                System.out.println("客户端说:" + funcByteToStr(receiveData));
                String str=funcByteToStr(receiveData);
                if (str.equals("bye")){
                    mSocket.close();
                    return;
                }
                HandleThread handleThread = new HandleThread(receivePacket);
                handleThread.setPriority(4);
                handleThread.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mSocket.close();// 关闭资源
        }
    }

    public static String funcByteToStr(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
            }
            return new String(buffer,0,length);
        } catch (Exception e) {
            return "";
        }
    }


    static class HandleThread extends Thread {
        private DatagramPacket mPacket;
        private DatagramSocket mSocket;

        public HandleThread(DatagramPacket packet) {
            super();
            mPacket = packet;
        }

        @Override
        public void run() {
            try {
                mSocket = new DatagramSocket();
                mSocket.send(mPacket);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (mSocket != null) {
                    mSocket.close();// 关闭资源
                }
            }
        }
    }
}
